import requests
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.urls import reverse
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from social.account.models import User
from social.im.tasks import send_tip_message
from social.rdm.models import ChatCountRdm
from social.user.models import UserBlock, UserLike
from social.utils.shortcut import get_object_or_none
from social.utils.views import BaseGenericViewSet


class MessageViewSet(BaseGenericViewSet):
    queryset = User.objects.all()
    permission_classes = (AllowAny,)

    @action(methods=['POST'], detail=False)
    def receive(self, request, *args, **kwargs):
        data = request.data
        from_id = data.get('from_user_id')
        to_id = data.get('conv_id')
        if from_id.startswith('holo'):
            r = requests.post('http://holo-api.memeapp.com.cn:8081/api/im/receive/', json=request.data)
            r.raise_for_status()
            return JsonResponse(data=r.json())
        from_user = User.get_user_by_im_id(from_id)
        to_user = User.get_user_by_im_id(to_id)
        if UserBlock.is_block(to_user, from_user):
            send_tip_message.delay(to_id, from_id, '发送失败，对方已拉黑了您')
            return JsonResponse(data={'result': 2})

        is_friend = get_object_or_none(UserLike, from_user=from_user, to_user=to_user, is_friend=True)
        if not is_friend:
            count = ChatCountRdm.get_chat_count(from_id, to_id)
            if count >= 3:
                send_tip_message.delay(to_id, from_id, '发送失败，非好友同一用户每天只能发送3条消息')
                return JsonResponse(data={'result': 2})
            else:
                ChatCountRdm.set_chat_count(from_id, to_id, count + 1)
        return Response()
